package top.kaoshanji.p2ch08a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * 代码清单-p2ch08a-03-252页a：Java编译器API的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/21 20:01
 */
public class JavaCompilerExample01 {

    private static final Logger logger = LogManager.getLogger(JavaCompilerExample01.class);

    public static void main(String[] args) {
        logger.info("...代码清单-p2ch08a-03-252页a：Java编译器API的使用示例...");

        // 输入的Java源代码的路径
        Path src = Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("Hellop2ch08a03.java"));

        // 编译之后产生的class文件的输出路径
        Path output = Paths.get(FileConstant.LOCAL_ROOT_PATH);

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(src.toFile());

            Iterable<String> options = Arrays.asList("-d", output.toString());

            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
            boolean call = task.call();
            logger.info("...call:{}...", call);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
